from django.shortcuts import render
from elasticsearch import Elasticsearch
from django.http.response import JsonResponse
import math

# Create your views here.
es = Elasticsearch(hosts=['http://127.0.0.1:9200'])


def index(request):
    if request.method == 'POST':
        if request.POST.get('id'):
            id = request.POST.get('id')
            keyword = request.POST.get('keyword')
            res = get_detail(id,keyword)
            return JsonResponse(res)
        if request.POST.get('init') == 'init':
            res = get_data(1, '', '全部', '1')
            print(res,type(res))
            res['open'] = True
            total = res['hits']['total']['value']
            res['page_html'] = get_paging(1, total)
            return JsonResponse(res)
        keyword = request.POST.get('keyword')
        type_ = request.POST.get('type')
        init = request.POST.get('init')
        page = request.POST.get('page')
        res = get_data(init, keyword, type_, page)
        total = res['hits']['total']['value']
        res['page_html'] = get_paging(page, total)
        return JsonResponse(res)
    else:
        return render(request, 'index.html')


def get_data(init, keyword, type_, page, size=20):
    query = {
        'bool': {
            'must': [
                {
                    'range': {
                        'time': {
                            'lte': 'now/d'
                        }
                    }
                }
            ],
            'should': []

        }
    }
    if init and '全部' in type_:
        res = es.search(
            index='bid',
            size=size,
            from_=0,
            track_total_hits=True,
            query=query,
            _source=['time', 'title', 'classification'],
            sort={"time": {"order": "desc"}}
        )
        return dict(res)
    if keyword:
        query['bool']['should'].append(
            {
                "multi_match": {
                    "query": keyword,
                    "type": "cross_fields",
                    "operator": "and",
                    # "minimum_should_match": "100%",
                    "fields": ["title", "classification"]
                },
            }
        )
        query['bool']['should'].append(
            {
                "match_phrase": {
                        "content": {
                            "query": keyword,
                            "slop": 3,
                        }
                    }
            },
        )
        query['bool']["minimum_should_match"]=1
    else:
        query['bool']['must'].append({
            'match_all': {}
        })
    if type_ != '9':
        query['bool']['must'].append(
            {
                'term': {
                    'typ': type_
                }
            }
        )
    res = es.search(size=size,
                    from_=(int(page) - 1) * 20,
                    track_total_hits=True,
                    _source=['time', 'title', 'classification'],
                    index='bid',
                    query=query,
                    highlight={"pre_tags": "<b style=\"color:red\">", "post_tags": "</b>",
                               "fields": {"title": {'fragment_size': 100000}, "classification": {'fragment_size': 100000}, "content": {'fragment_size': 100000}}},
                    sort=[
                        {'time': 'desc'},
                    ]
                    )
    print(res)
    return dict(res)


def get_paging(page_, total, num=20):
    page = math.ceil(int(total) / num)
    page_ = int(page_)
    page_html = ''
    if page_ == 1:
        page_html = '<li class="page-item active"><a class="page-link">1</a></li>'
    else:
        page_html += '<li class="page-item"><a class="page-link" href="#">上一页</a></li>'
        page_html += f'<li class="page-item active"><a class="page-link">{page_}</a></li>'
    if page_ != page:
        page_html += '<li class="page-item"><a class="page-link" href="#">下一页</a></li>'
    return page_html


def get_detail(id,keyword):
    if keyword:
        res_ = es.search(index='bid',
                        query={
                            'bool': {
                                'must': {
                                    'term': {
                                        '_id': id
                                    }
                                },
                                'should': [
                                    {
                                        'match': {'content': keyword}
                                    },
                                    {
                                        'match': {'title': keyword}
                                    }
                                ]
                            }
                        },
                        highlight={
                            "pre_tags": "<b style='color:red'>",
                            "post_tags": "</b>",
                            "fields": {
                                "title": {'fragment_size': 100000},
                                "content": {'fragment_size': 100000}
                            }
                        })

        res = dict(res_)['hits']['hits'][0]['_source']
        for k in res:
            if k in res_['hits']['hits'][0]['highlight']:
                res[k] = res_['hits']['hits'][0]['highlight'][k][0]
    else:
        res = dict(es.get_source(index='bid', id=id))
    try:
        dic = res['hits']['hits'][0]['_source']
    except:
        dic = res
    t_dic = {
        'price': '金额',
        'pricetype': '金额单位',
        'zhaobiao_person': '招标人',
        'project_code': '项目编号',
        'succ_bidder_person': '中标单位',
        'zhaobiao_contactor': '招标联系人',
        'zhaobiao_phone': '招标联系电话',
        'zhaobiao_address': '招标联系地址',
        'agency_danwei': '招标代理单位',
        'agency_contactor': '招标代理联系人',
        'agency_phone': '招标代理联系电话',
        'agency_address': '招标代理联系地址',
    }
    if len([x for x in dic.keys() if x in t_dic.keys()]) > 0:
        tab = '<div><table class="table table-bordered">'
        num = 0
        for k, v in dic.items():
            if k in t_dic and v != '':
                num += 1
                if num % 2:
                    tab += f'<tr><td><b>{t_dic[k]}</b></td><td>{v}</td>'
                else:
                    tab += f'<td><b>{t_dic[k]}</b></td><td>{v}</td></tr>'
        if tab.endswith('</tr>'):
            tab += '</table></div>'
        else:
            tab += '<tb></tb></tr></table></div>'
        print(res,type(res))
        res['table']=tab
    return res
